package logger.sd.server.service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import logger.sd.protocol.LRP;
import logger.sd.server.LoggingServer;
import logger.sd.server.ServerConfiguration;

public class TokenSenderService extends TimerTask implements Service,
		TokenSender {

	private Long time;
	private LoggingServer server;
	private final Timer timer = new Timer();
	private ServerConfiguration config;

	/**
	 * Construtor.
	 * 
	 * @param server
	 */
	public TokenSenderService(LoggingServer server) {
		config = server.getConfig();
		this.server = server;
		this.time = config.getTokentime();
	}

	/**
	 * Construtor Deprecated por que o time eh pego no arquivo de configuracao
	 * 
	 * @param server
	 * @param time
	 */
	@Deprecated
	public TokenSenderService(LoggingServer server, Long time) {
		this.server = server;
		this.time = time;
	}

	/**
	 * Basicamente agenda o envio dos tokens
	 */
	@Override
	public String trataRequisicao() {
		this.schedule();
		return LRP.okMessage();
	}

	/**
	 * Programa o TokenSender para que ele envie os tokens! Agenda o envio do
	 * token no periodo definido em <code>this.time</code>
	 */
	@Override
	public void schedule() {
		timer.schedule(this, this.time);
	}

	@Override
	public String getRequest() {
		return null;
	}

	@Override
	public void run() {
		sendToken();
	}

	/**
	 * Envia o token ao proximo server
	 */
	public void sendToken() {
		try {
			if (config.getNextPortServer() != 0 && server.hasToken()) {

				Socket nextServerSocket = new Socket(
						config.getNextHostServer(), config.getNextPortServer());

				BufferedReader inFromServer = new BufferedReader(
						new InputStreamReader(nextServerSocket.
								getInputStream()));

				DataOutputStream outToServer = new DataOutputStream(
						nextServerSocket.getOutputStream());

				outToServer.writeBytes(LRP.TOKEN.getMessage() + ':'
						+ LRP.TOKENARRIVE.getMessage() + '\n');

				String resposta = inFromServer.readLine();

				if (resposta.equals(LRP.okMessage())) {
					server.passarToken();
				}
				nextServerSocket.close();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public String getCode() {
		return LRP.TOKEN.getMessage();
	}

}
